package com.csx.base.core.algorithm.list;

/**
 * <p> 合并两个有序链表:
 * <p>     将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 * <p> 例如:
 * <p> 输入：l1 = [1,2,4], l2 = [1,3,4]
 * <p> 输出：[1,1,2,3,4,4]
 * @author cuisongxu
 * @date 2024/3/2 周六 10:56
 */
public class MergeTwoLists {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(4);

        ListNode node4 = new ListNode(1);
        ListNode node5 = new ListNode(3);
        ListNode node6 = new ListNode(4);


        node1.next = node2;
        node2.next = node3;

        node4.next = node5;
        node5.next = node6;

        MergeTwoLists mergeTwoLists = new MergeTwoLists();
        ListNode listNode = mergeTwoLists.mergeTwoLists2(node1, node4);
        System.out.println(listNode);

    }

    /**
     * 迭代
     * 时间复杂度: O(n)
     * 空间复杂度: O(n)
     * @param list1
     * @param list2
     * @return
     */
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null) {
            return list2;
        }

        if(list2 == null) {
            return list1;
        }
        ListNode currentNode = null;
        ListNode tempNode = null;
        ListNode res = null;
        while (list1 != null && list2 != null) {
            int list1Value = list1.val;
            int list2Value = list2.val;
            if(list1Value <= list2Value) {
                currentNode = new ListNode(list1.val);
                list1 = list1.next;
            }else {
                currentNode = new ListNode(list2.val);
                list2 = list2.next;
            }

            if(tempNode == null) {
                tempNode = currentNode;
                res = tempNode;

            }else {
                tempNode.next = currentNode;
                tempNode = tempNode.next;
            }
        }

        if(list1 != null) {
            tempNode.next = list1;
        }

        if(list2 != null) {
            tempNode.next = list2;
        }

        return res;
    }

    /**
     * 递归法
     * 时间复杂度: O(n)
     * 空间复杂度: O(n)
     * @param list1
     * @param list2
     * @return
     */
    public ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
        if(list1 == null) {
            return list2;
        }

        if(list2 == null) {
            return list1;
        }

        if(list1.val <= list2.val) {
            list1.next = mergeTwoLists2(list1.next, list2);
            return list1;
        }else {
            list2.next = mergeTwoLists2(list1, list2.next);
            return list2;
        }
    }
}
